package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.ClassHasStudentsException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.QueryParam;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult page(QueryParam queryParam) {
        //1.处理page和pageSize
        PageHelper.startPage(queryParam.getPage(),queryParam.getPageSize());
        //2.调用mapper方法执行查询
        List<Clazz> clazzList =  clazzMapper.list(queryParam);
        //将得到的List转换成Page集合
        Page<Clazz> p = (Page<Clazz>) clazzList;
        //返回封装的页面信息
        return new PageResult(p.getTotal(),p.getResult());
    }

    @Override
    public void addClazz(Clazz clazz) {
        //补全时间信息
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public void delete(Integer id) {
        // 检查该班级下是否有学生
        int studentCount = studentMapper.countByClassId(id);
        if (studentCount > 0) {
            throw new ClassHasStudentsException("对不起, 该班级下有学生, 不能直接删除");
        }

        // 如果没有学生，执行删除
        clazzMapper.deleteById(id);
    }

    @Override
    public List<Clazz> getAll() {
        return clazzMapper.getALl();
    }
}
